package cn.interestingshop.web.client;

import cn.interestingshop.entity.*;
import cn.interestingshop.entity.vo.Cart;
import cn.interestingshop.entity.vo.GoodsList;
import cn.interestingshop.service.baseOrder.BaseOrderService;
import cn.interestingshop.service.baseOrder.BaseOrderServiceImpl;
import cn.interestingshop.service.classify.ClassifyService;
import cn.interestingshop.service.classify.ClassifyServiceImpl;
import cn.interestingshop.service.goods.GoodsService;
import cn.interestingshop.service.goods.GoodsServiceImpl;
import cn.interestingshop.service.notice.NoticeService;
import cn.interestingshop.service.notice.NoticeSserviceImpl;
import cn.interestingshop.service.orderInfo.OrderInfoService;
import cn.interestingshop.service.orderInfo.OrderInfoServiceImpl;
import cn.interestingshop.service.userAddress.UserAddressService;
import cn.interestingshop.service.userAddress.UserAddressServiceImpl;
import cn.interestingshop.utils.ClassifyVo;
import cn.interestingshop.utils.DdhUtils;
import cn.interestingshop.utils.EmptyUtils;
import cn.interestingshop.utils.JedisUtil;
import cn.interestingshop.web.AbstractServlet;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "CartServlet",urlPatterns = "/cart")
public class CartServlet extends AbstractServlet {
    @Override
    public Class getServletClass() {
        return CartServlet.class;
    }

    public void add(HttpServletRequest request, HttpServletResponse response){

        JSONObject jsonObject=new JSONObject();

        if(!EmptyUtils.isEmpty(request.getSession().getAttribute("loginUser"))){




            Cart cart=new Cart();

            List<GoodsList> goodsList=new ArrayList<>();

            int id= Integer.parseInt(request.getParameter("entityId"));
            int stock= Integer.parseInt(request.getParameter("buyNum"));



            boolean ok=false;
            boolean stockNo=false;
        if(!EmptyUtils.isEmpty(request.getSession().getAttribute("cart"))){
            cart= (Cart) request.getSession().getAttribute("cart");
            goodsList=cart.getShopGoodsList();
            for (GoodsList list : goodsList) {
                if(list.getGoods().getId()==id){
                    ok=true;
                    if(list.getGoods().getStock()<stock){
                        stockNo=true;
                        break;
                    }
                    list.setBuyNum(list.getBuyNum()+stock);
                    cart.setSum(cart.getSum()+(stock*list.getGoods().getPrice()));
                    break;
                }
            }
        }



        if(ok==false) {
            GoodsList goodsList1 = new GoodsList();
            goodsList1.setBuyNum(stock);

            Goods goods2 = null;

            GoodsService goodsService = new GoodsServiceImpl();

            goods2 = goodsService.selectOne(id);

            if(goods2.getStock()<stock){
                stockNo=true;
            }

            if(stockNo==false) {
                goodsList1.setGoods(goods2);

                goodsList.add(goodsList1);


                if (EmptyUtils.isEmpty(request.getSession().getAttribute("sum"))) {
                    cart.setSum(stock * goods2.getPrice());
                } else {
                    cart.setSum(Float.parseFloat(String.valueOf(request.getSession().getAttribute("sum"))) + (stock * goods2.getPrice()));
                }
            }

        }

        if(stockNo==false) {
            cart.setShopGoodsList(goodsList);

            request.getSession().setAttribute("sum", cart.getSum());
            request.getSession().setAttribute("cart", cart);

            if(!EmptyUtils.isEmpty(cart)){
                jsonObject.put("status",1);
            }else{
                jsonObject.put("status",0);
                jsonObject.put("message","添加购物车失败");
            }

        }else{
            jsonObject.put("status",0);
            jsonObject.put("message","购买的数量大于商品数量");
        }




        }else{
            jsonObject.put("status",0);
            jsonObject.put("message","请登录!");
        }


        try {
        response.getWriter().print(jsonObject);
        } catch (IOException e) {
        e.printStackTrace();
    }



    }


    public String toSettlement(HttpServletRequest request,HttpServletResponse response){
        ClassifyService classifyService=new ClassifyServiceImpl();

        List<ClassifyVo> list = classifyService.selectAll();

        NoticeService noticeService=new NoticeSserviceImpl();
        List<Notice> list1 = noticeService.selectAll();

        request.setAttribute("notice",list1);

        request.setAttribute("classifyVoList",list);
        request.setAttribute("yema",1);

        return "client/settlement/toSettlement";
    }

    public String settlement2(HttpServletRequest request,HttpServletResponse response){


        ClassifyService classifyService=new ClassifyServiceImpl();

        List<ClassifyVo> list = classifyService.selectAll();

        NoticeService noticeService=new NoticeSserviceImpl();
        List<Notice> list1 = noticeService.selectAll();

        request.setAttribute("notice",list1);

        request.setAttribute("classifyVoList",list);

        request.setAttribute("yema",2);
        UserAddressService userAddressService=new UserAddressServiceImpl();
        
        User user= (User) request.getSession().getAttribute("loginUser");

        List<UserAddress> userAddress = userAddressService.selectOne(user.getId());

        request.setAttribute("userAddressList",userAddress);



        return "client/settlement/toSettlement";
    }

    public void settlement3(HttpServletRequest request,HttpServletResponse response){



        User user= (User) request.getSession().getAttribute("loginUser");
        int addressId= Integer.parseInt(request.getParameter("addressId"));
        String newAddress=request.getParameter("newAddress");
        String newRemark=request.getParameter("newRemark");

        UserAddress userAddress=new UserAddress();

        int userId=0;


        BaseOrderService baseOrderService = new BaseOrderServiceImpl();

        BaseOrder baseOrder = new BaseOrder();

        Cart cart= (Cart) request.getSession().getAttribute("cart");
        userId= user.getId();
        if(addressId==-1) {

            UserAddressService userAddressService=new UserAddressServiceImpl();

            addressId=user.getId();

            int rs=0;
            rs=userAddressService.insert(addressId,newAddress,newRemark);

            baseOrder.setUserId(userId);
            baseOrder.setAccount(user.getAccount());
            baseOrder.setUserAddress(newAddress);
            baseOrder.setAmount(cart.getSum());
            baseOrder.setOrderNo(DdhUtils.getOrderCode(addressId));
        }else{
            UserAddressService userAddressService=new UserAddressServiceImpl();

             userAddress= userAddressService.selectOneid(addressId);


            baseOrder.setUserId(userId);
            baseOrder.setAccount(user.getAccount());


            baseOrder.setUserAddress(userAddress.getAddress());

            baseOrder.setAmount(cart.getSum());
            baseOrder.setOrderNo(DdhUtils.getOrderCode(addressId));
        }









            int insert =0;
            insert=baseOrderService.insert(baseOrder);

            OrderInfoService orderInfoService=new OrderInfoServiceImpl();
            GoodsService goodsService=new GoodsServiceImpl();

            int orderInsert=0;

            if(insert!=0){
                for (GoodsList goodsList : cart.getShopGoodsList()) {
                    OrderInfo orderInfo=new OrderInfo();

                    orderInfo.setBaseOrderId(insert);
                    orderInfo.setGoodsId(goodsList.getGoods().getId());
                    orderInfo.setBuyNum(goodsList.getBuyNum());
                    orderInfo.setAmount(goodsList.getGoods().getPrice()*goodsList.getBuyNum());

                    orderInsert=orderInfoService.insert(orderInfo);

                    goodsService.kjKc(goodsList.getGoods().getId(),goodsList.getBuyNum());
                }

            }




            request.getSession().setAttribute("baseOrderId",insert);


            JSONObject jsonObject=new JSONObject();
            if(orderInsert!=0){
                jsonObject.put("status",1);
                JedisUtil.getJedis().del("classifyVoList");
                JedisUtil.getJedis().del("notice");
            }else{
                jsonObject.put("status",0);
                jsonObject.put("message","添加订单失败");
            }

        try {
            response.getWriter().print(jsonObject);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public String settlement33(HttpServletRequest request,HttpServletResponse response) {

        BaseOrderService baseOrderService=new BaseOrderServiceImpl();

        BaseOrder baseOrder2=baseOrderService.selectOne((Integer) request.getSession().getAttribute("baseOrderId"));

        request.getSession().removeAttribute("cart");

        ClassifyService classifyService=new ClassifyServiceImpl();

        List<ClassifyVo> list = classifyService.selectAll();

        NoticeService noticeService=new NoticeSserviceImpl();
        List<Notice> list1 = noticeService.selectAll();

        request.setAttribute("notice",list1);

        request.setAttribute("classifyVoList",list);
        request.setAttribute("yema",3);
        request.setAttribute("currentOrder",baseOrder2);


        return "client/settlement/toSettlement";
    }



    public void del(HttpServletRequest request,HttpServletResponse response){

        Cart cart=new Cart();

        List<GoodsList> goodsList=new ArrayList<>();

        int id=Integer.parseInt(request.getParameter("entityId"));

        JSONObject jsonObject=new JSONObject();

        boolean ok=false;

        if(!EmptyUtils.isEmpty(request.getSession().getAttribute("cart"))){
            cart= (Cart) request.getSession().getAttribute("cart");
            goodsList=cart.getShopGoodsList();
            for (GoodsList list : goodsList) {
                if(list.getGoods().getId()==id){


                    cart.setSum(cart.getSum()-(list.getGoods().getPrice()*list.getBuyNum()));
                    goodsList.remove(list);
                    cart.setShopGoodsList(goodsList);
                    request.getSession().setAttribute("cart",cart);
                    request.getSession().setAttribute("sum",cart.getSum());
                    ok=true;
                    break;
                }
            }
        }

        if(ok==true){
            jsonObject.put("status",1);
            if(goodsList.size()<=0){
                request.getSession().removeAttribute("cart");
                request.getSession().removeAttribute("sum");
            }
        }else{
            jsonObject.put("status",0);
            jsonObject.put("message","删除失败");
        }

        try {
            response.getWriter().print(jsonObject);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void modCart(HttpServletRequest request,HttpServletResponse response){
        Cart cart=new Cart();

        List<GoodsList> goodsList=new ArrayList<>();

        int id=Integer.parseInt(request.getParameter("entityId"));
        int buyNum=Integer.parseInt(request.getParameter("buyNum"));

        JSONObject jsonObject=new JSONObject();

        boolean ok=false;

        if(!EmptyUtils.isEmpty(request.getSession().getAttribute("cart"))){
            cart= (Cart) request.getSession().getAttribute("cart");
            goodsList=cart.getShopGoodsList();
            for (GoodsList list : goodsList) {
                if(list.getGoods().getId()==id){
                    int a1=list.getBuyNum();
                    list.setBuyNum(buyNum);
                    if(request.getParameter("jj").equals("+")){
                        cart.setSum(cart.getSum()+((list.getBuyNum()-a1)*list.getGoods().getPrice()));
                    }else{
                        cart.setSum(cart.getSum()-((a1-list.getBuyNum())*list.getGoods().getPrice()));
                    }

                    ok=true;
                    break;
                }
            }
        }

        if(ok==true){
            jsonObject.put("status",1);
        }else{
            jsonObject.put("status",0);
            jsonObject.put("message","修改失败");
        }

        try {
            response.getWriter().print(jsonObject);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
